package com.party.mobile.biz.analysis;

import com.party.common.paging.Page;
import com.party.common.utils.DateUtils;
import com.party.common.utils.StringUtils;
import com.party.core.model.analysis.StatisticsEvent;
import com.party.core.model.analysis.StatisticsEventCounter;
import com.party.core.model.analysis.StatisticsEventFlow;
import com.party.core.model.analysis.StatisticsMobileEventCounter;
import com.party.core.service.analysis.IStatisticsEventCountService;
import com.party.core.service.analysis.IStatisticsEventFlowService;
import com.party.core.service.analysis.IStatisticsEventService;
import com.party.core.service.analysis.IStatisticsMobileEventCountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: Project
 * @description: 统计事件流程业务接口实现
 * @author: Huaqunhao
 * @create: 2018-08-10 10:50
 **/
@Service
public class StatisticalEventFlowBizService {
    @Autowired
    private IStatisticsEventFlowService statisticsEventFlowService;
    @Autowired
    private StatisticsFlowBizService statisticsFlowBizService;
    @Autowired
    private IStatisticsEventService statisticsEventService;
    @Autowired
    private IStatisticsEventService iStatisticsEventService;
    @Autowired
    private IStatisticsEventCountService iStatisticsEventCountService;
    @Autowired
    private IStatisticsMobileEventCountService statisticsMobileEventCountService;

    /**
     * @Description: 通过cookie里面的uniqueCode生成事件流程数据
     * @Param: eventId 事件ID
     * @Param: pCode 上个事件流程id
     * @Param: orgId 机构id
     * @return:
     * @Author: Huaqunhao
     * @Date: 2018/8/10/010
     */
    public void innerEventFlowDataReport(String eventId, String pCode, String orgId, String userId, HttpServletRequest request, HttpServletResponse response) {
        StatisticsEventFlow sef = new StatisticsEventFlow();
        String uniqueCode = this.getUniqueCode(userId, pCode, request, response);

        //StatisticsEventFlow dbSEFs = statisticsEventFlowService.getNewFlow(uniqueCode);

        //第一次请求-------事件的开端
/*        if (null == dbSEFs) {*/
        sef.setUserId(userId);
/*        }
        //再次请求--------事件ing
        else {
            //通过uniqueCode获取上级节点
            StatisticsEventFlow seft_current = dbSEFs;

            if (null != seft_current) {
                String parentIds = seft_current.getParentIds();
                if (StringUtils.isEmpty(parentIds)) {
                    sef.setParentIds(seft_current.getEventId());
                } else {
                    sef.setParentIds(seft_current.getParentIds() + "," + seft_current.getEventId());
                }
                //设置当前节点
                sef.setUserId(seft_current.getUserId());
                sef.setParentId(seft_current.getEventId());
            }
        }*/
        sef.setPartnerId(orgId);
        sef.setEventId(eventId);
        sef.setUniqueCode(uniqueCode);
        statisticsEventFlowService.insert(sef);
    }

    /**
     * @Description:
     * @Param:
     * @return:
     * @Author: Huaqunhao
     * @Date: 2018/8/10/010
     */
    public String getUniqueCode(String userId, String pCode, HttpServletRequest request, HttpServletResponse response) {
        String uniqueCode = statisticsFlowBizService.getCookieByKey(request, statisticsFlowBizService.eventRedisKey);
        if (StringUtils.isEmpty(pCode) || StringUtils.isEmpty(uniqueCode)) {
            uniqueCode = statisticsFlowBizService.getUniqueCode(request.getRequestURI(), userId);
            Cookie cookie = new Cookie(statisticsFlowBizService.eventRedisKey, uniqueCode);
            cookie.setPath("/");
            //不设置周期
            response.addCookie(cookie);
        }
        return uniqueCode;
    }

    /**
     * @Description:定时任务维护事件data
     * @Param:
     * @return:
     * @Author: Huaqunhao
     * @Date: 2018/9/12/010
     */
    public void eventDataMaintenance() {
        //获取昨天的日期
        String yesterday = DateUtils.formatDate(DateUtils.yesterday());

        String startDate = yesterday + " 00:00:00";
        String endDate = yesterday + " 23:59:59";
        //获取昨天的事件总数
        int totalCount = statisticsEventFlowService.queryEventTotalNumByDate(startDate, endDate);

        Page page = new Page();
        page.setPage(1);
        page.setLimit(1000);
        page.setTotalCount(totalCount);

        for (int i = 1; i <= page.getTotalPages(); i++) {
            page.setPage(i);
            List<StatisticsEventFlow> selist = statisticsEventFlowService.queryEventBydate(startDate, endDate, page.getOffset(), page.getLimit());

            for (int j = 0; j < selist.size(); j++) {

                StatisticsEventFlow sefObj = selist.get(j);

                StatisticsEventFlow sefObj_before = null;
                if (j != 0) {
                    sefObj_before = selist.get(j - 1);
                }

                //过滤第一个
                //过滤不是一个UniqueCode的
                if (0 != j &&
                        sefObj_before != null &&
                        sefObj.getUniqueCode().equals(sefObj_before.getUniqueCode())) {

                    //设置ParentId
                    sefObj.setParentId(sefObj_before.getEventId());

                    //设置ParentIds
                    if (StringUtils.isNotBlank(sefObj_before.getParentIds())) {

                        sefObj.setParentIds(sefObj_before.getParentIds() + "," + sefObj_before.getEventId());

                    } else {
                        sefObj.setParentIds(sefObj_before.getEventId());
                    }
                    statisticsEventFlowService.update(sefObj);
                }
            }
        }
    }

    public void analysWebEvent(Date queryDate, String date) {
        Map<String, Object> map = new HashMap<>();
        map.put("startDate", date + " 00:00:00");
        map.put("endDate", date + " 23:59:59");
        List<StatisticsEvent> eventList = iStatisticsEventService.countList(map);
        //以下插入所有日期的事件统计数据
        eventList.stream().forEach(event -> {
            StatisticsEventCounter eventCounter = new StatisticsEventCounter();
            eventCounter.setEventId(event.getId());
            eventCounter.setEventName(event.getName());
            eventCounter.setEventCode(event.getCode());
            eventCounter.setEventNum(event.getEventNum().intValue());
            eventCounter.setUserNum(event.getOnUserEventNum().intValue());
            eventCounter.setCreateDate(queryDate);
            eventCounter.setCreateBy("system task");
            eventCounter.setUpdateBy("system task");
            iStatisticsEventCountService.insert(eventCounter);
        });
    }

    public void analysMobileEvent(Date queryDate, String date) {
        Map<String, Object> map = new HashMap<>();
        map.put("startDate", date + " 00:00:00");
        map.put("endDate", date + " 23:59:59");
        List<StatisticsMobileEventCounter> eventList = statisticsMobileEventCountService.mobileCountList(map);
        for (StatisticsMobileEventCounter eventCounter : eventList) {
            eventCounter.setCreateDate(queryDate);
            eventCounter.setCreateBy("system task");
            eventCounter.setUpdateBy("system task");
            statisticsMobileEventCountService.insert(eventCounter);
        }
    }
}
